package com.quanyan.ic.vendingMachine.protocol.server.handler;

import com.alibaba.fastjson.JSON;
import com.quanyan.ic.vendingMachine.dao.VmPlaceMappingDAO;
import com.quanyan.ic.vendingMachine.model.VmPlaceMapping;
import com.quanyan.ic.vendingMachine.protocol.Cmd;
import com.quanyan.ic.vendingMachine.protocol.Code;
import com.quanyan.ic.vendingMachine.protocol.codec.protobuf.VmMessageBuilder;
import com.quanyan.ic.vendingMachine.protocol.codec.protobuf.VmMessageProto;
import com.quanyan.ic.vendingMachine.protocol.server.session.Session;
import com.quanyan.ic.vendingMachine.protocol.server.session.SessionManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by zhuo.shi on 2017/7/31.
 */
@Component("HeartBeatRespHandler")
@ChannelHandler.Sharable
public class HeartBeatRespHandler extends ChannelInboundHandlerAdapter {

    public static final Logger logger = LoggerFactory.getLogger(HeartBeatRespHandler.class);

    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private VmPlaceMappingDAO vmPlaceMappingDAO;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        VmMessageProto.VmMessage vmMessage = (VmMessageProto.VmMessage) msg;
        String vmNumber = vmMessage.getVmNumber();
        if (vmMessage.getCmd() == Cmd.HEARTBEAT_REQ.getValue()) {
            logger.info("received cmd {}\n{}", Cmd.HEARTBEAT_REQ.getDesc(), vmMessage);
            if (sessionManager.get(vmNumber) == null) {
                VmPlaceMapping mapping = vmPlaceMappingDAO.findByVmNumber(vmNumber);
                if (mapping != null && mapping.getInUse()) {
                    Session session = new Session();
                    session.setId(vmNumber);
                    session.setChannel(ctx.channel());
                    session.setLastCommunicateTimeStamp(System.currentTimeMillis());
                    sessionManager.save(session);
                    logger.info("add session {}", JSON.toJSONString(session));
                }
            }
            ctx.writeAndFlush(      //应答握手消息
                    new VmMessageBuilder(vmNumber)
                            .buildRespCode(Code.RC_200)
                            .buildCmd(Cmd.HEARTBEAT_RESP).getMessage()
            );
        } else {
            ctx.fireChannelRead(msg);
        }
    }
}
